from flask import render_template, abort, g, request, jsonify, current_app

from info import db
from info.constants import HOME_PAGE_MAX_NEWS
from info.models import News, Comment, User
from info.modules.news import news_blu
from info.utils.common import user_login_data
from info.utils.response_code import RET, error_map


@news_blu.route('/<int:news_id>', methods=['GET'])
@user_login_data
def news_detail(news_id):

    from flask import current_app
    try:
        news = News.query.get(news_id)  # 这里是个对象
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)

    news_list = []

    from flask import current_app
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(HOME_PAGE_MAX_NEWS).all()
    except BaseException as e:
        current_app.logger.error(e)


    user =g.user
    is_collection = False
    if user:
        if news in user.collection_news:
            is_collection = True

    comments = news.comments.order_by(Comment.create_time.desc()).all()
    # comment_list = [comment.to_dict() for comment in comments]


    #　查询那些评论被当前用户点过赞
    comment_list = []
    for comment in comments:
        is_like = False # 是否被我点赞
        comment_dict = comment.to_dict()

        if user:

            if comment in user.like_comments:
                is_like = True

        comment_dict['is_like'] = is_like
        comment_list.append(comment_dict)


    # 这里新写的－－－－－－－－－－－－－－－－－－－－－
    is_followed = False
    if news.user and user:
        if news.user in user.followed:
            is_followed = True

    news_list = [news.to_dict() for news in news_list] # 把新闻对象列表，转成字典列表

    user = g.user.to_dict() if g.user else None #　如果g.user不是none 转成字典赋值给user, 是的话就把none　给user

    news.clicks += 1

    return render_template('news/detail.html', news=news.to_dict(), user=user, news_list=news_list, is_collection=is_collection, comment_list=comment_list, is_followed=is_followed)


@news_blu.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():
    # 取一下user对象
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])

    news_id = request.json.get('news_id')
    action = request.json.get('action')

    # 检验一下是否都存在，都存在的话把news_id转整数

    if not ([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        news_id = int(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        # 先要把新闻都查出来
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    if action == 'collect':
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


@news_blu.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():
    # 取一下user对象
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])

    news_id = request.json.get('news_id')
    comment_content = request.json.get('comment')
    parent_id = request.json.get('parent_id')

    print(news_id)
    print(comment_content)
    print(parent_id)


    # 校验参数
    if not all([news_id, comment_content]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])


    try:
        news_id = int(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])



    #　生成评论
    comment = Comment()
    comment.content = comment_content
    comment.news_id = news_id
    comment.user_id = user.id

    if parent_id:

        try:
            parent_id = int(parent_id)
            comment.parent_id = parent_id

        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])


    db.session.add(comment)

    try:
        db.session.commit()
    except BaseException as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=comment.to_dict())



@news_blu.route('/comment_like', methods=['POST'])
@user_login_data
def comment_like():
    # 取一下user对象
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])

    comment_id = request.json.get('comment_id')
    action = request.json.get('action')

    # 检验一下是否都存在，都存在的话把news_id转整数

    if not ([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        comment_id = int(comment_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    if action not in ['add', 'remove']:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        # 先要把新闻都查出来
        comment = Comment.query.get(comment_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    if action == 'add':
        user.like_comments.append(comment)
        comment.like_count += 1
    else:
        user.like_comments.remove(comment)
        comment.like_count -= 1
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])





@news_blu.route('/followed_user', methods=['POST'])
@user_login_data
def followed_user():
    # 取一下user对象
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map[RET.SESSIONERR])

    author_id = request.json.get('user_id')
    action = request.json.get('action')

    # 检验一下是否都存在，都存在的话把news_id转整数

    if not ([author_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        author_id = int(author_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    if action not in ['follow', 'unfollow']:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:

        author = User.query.get(author_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    if action == 'follow':
        user.followed.append(author)
    else:
        user.followed.remove(author)

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])













